package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        用来理解发来请求数据的字符集
        req.setCharacterEncoding("utf8");
//        用来设置发送响应的数据
        resp.setContentType("text/html; charset=utf8");
//        获取到发来请求的,用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || username.equals("") || password == null || password.equals("")) {
//            如果用户名,密码为空登录失败,或者为空字符串也视为登录失败
            String html = "<h3>登录失败,用户名或密码为空.</h3>";
            resp.getWriter().write(html);
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectByUserName(username);
        if (user == null) {
//            用户不存在
            String html = "<h3>登录失败,用户名或密码错误.</h3>";
            resp.getWriter().write(html);
            return;
        }
        if(!password.equals(user.getPassword())) {
//            密码错误
            String html = "<h3>登录失败,用户名或密码错误.</h3>";
            resp.getWriter().write(html);
            return;
        }
//        建立会话,用来保存用户信息
//        如果有旧的session就用旧的
//        如果没有就创建新的会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
//        登录成功后,重定向跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    private ObjectMapper objectMapper = new ObjectMapper();

//这里的get方法用来确认用户的登录状态
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        resp.setContentType("application/json; charset=utf8");
//        如果没有会话说明用户未登录
        if (session == null) {
//            返回未登录的响应
//            构造新的user这样返回的userId就为0
            User user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
//        获取到会话中用户的信息
        User user = (User) session.getAttribute("user");
        if (user == null) {
            user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
//        到这里说明已经登录了,有旧的会话直接返回获取的对象即可
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
